package com.example.administrator.text;

import android.content.ComponentName;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.Toast;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import app.BaseActivity;
import app.MyApplication;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import data.SharedPreferencesUtils;
import entity.Update;
import util.GreenTreeNetworkUtil;
import util.HomeUtil;
import util.JumpActivityUtils;
import util.LogUtil;
import util.RequestDataCallback;
import util.StringUtil;
import util.Url;
import util.getInformation;
import view.diaLogView.EditionDialog;
import view.diaLogView.RetunDialog;
import view.diaLogView.UploadDialog;

public class SetNewFiActivity extends BaseActivity {
    private ArrayList<String> mList = new ArrayList<>();
    private UploadDialog mUploadDialog;
    private List<Update> mUpdateList;
    private EditionDialog mUpdateDialog;
    private RetunDialog mRetunDialog;
    private int mPwd;
    private boolean mState = false;  //记录退出是否被点击过

    @Bind(R.id.activity_setnewfi_frame)  FrameLayout mFrameLoayout;
    @Bind(R.id.activity_setnewfi_list)   ListView mListView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setnewfi);
        ButterKnife.bind(this);
        init();
    }

    private void init() {
        HomeUtil.getHemeUtilNew().getStatusBar(this, mFrameLoayout);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(
                this,
                R.layout.adapter_setnet_list,
                R.id.adapter_list_tv_name,
                getData());
        mListView.setAdapter(adapter);

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position){
                    case 0:
                        JumpActivityUtils.getInstance().jumpProblemItem(SetNewFiActivity.this,"关于我们");
                        break;
                    case 1:
                        update();
                        break;
                    case 2:
                        String id1 = (String) SharedPreferencesUtils.getParam(SetNewFiActivity.this, HomeUtil.mUseridDB, "");
                        String token = (String) SharedPreferencesUtils.getParam(SetNewFiActivity.this, HomeUtil.mTokenDB, "");
                        String url = Url.mATIAIRIP + Url.getUrlNew().login_VerifyLogin+"?userid="+id1+"&token="+token;
                        JumpActivityUtils.getInstance().jumpWebView(SetNewFiActivity.this,url,"后台管理");
                        break;
                    case 3:
                        JumpActivityUtils.getInstance().jumpPing(SetNewFiActivity.this);
                        break;
                }
            }
        });
    }

    /**
     * 返回
     */
    @OnClick(R.id.activity_setnewfi_ll)
    void getFinish(){
        finish();
    }

    /**
     * 退出
     * 如果没有设置密码就去提示设置密码
     */
    @OnClick(R.id.linear_setnewfi_out)
    void weinformationOut(){

        mPwd = (int) SharedPreferencesUtils.getParam(this, ModifyInformationActivity.PWD,1);  //密码
        if(mPwd == 1){

            String fwq = (String) SharedPreferencesUtils.getParam(this, HomeUtil.mFWQ,"");
            if(fwq.equals("")){
                fwq = MyApplication.getApp().getFWQString();
            }
            if(mRetunDialog == null){
                mRetunDialog = new RetunDialog(this,fwq,0,false);
                mRetunDialog.show();
            }else {
                mRetunDialog.show();
            }

        }else {
            if(!mState){
                mState = true;
                getToast("您还未设置密码请先设置密码");
                JumpActivityUtils.getInstance().jumpModifypassword1(SetNewFiActivity.this, ModifyInformationActivity.PWD);
            }else {
                String fwq = (String) SharedPreferencesUtils.getParam(this, HomeUtil.mFWQ,"");
                if(fwq.equals("")){
                    fwq = MyApplication.getApp().getFWQString();
                }

                if(mRetunDialog == null){
                    mRetunDialog = new RetunDialog(this,fwq,0,false);
                    mRetunDialog.show();
                }else {
                    mRetunDialog.show();
                }
            }
        }
    }

    private ArrayList<String> getData()
    {
        mList.add("关于我们");
        mList.add("新版本");
        mList.add("后台管理");
        mList.add("检查网络");
        return mList;
    }

    /**
     * 更新版本
     * 0 从域名进来
     * 1 从代理进来
     */
    private void update() {

        if(mUploadDialog == null){
            mUploadDialog = new UploadDialog(this,"查询中");
            mUploadDialog.show();
        }else {
            mUploadDialog.show();
        }
        mUpdateList = new ArrayList<>();
        mMap = new HashMap<>();
        LogUtil.eE("mFWQString", "   WELC2   " + MyApplication.getApp().getFWQString());
        mMap.put("ver", getInformation.getNewGetInformation(this).getVersion());
        mMap.put("vertype",1);
            if(MyApplication.getApp().getFWQString().contains(":8")){
                String agencyIp = MyApplication.getApp().getFWQString().substring(0, MyApplication.getApp().getFWQString().indexOf(":8"))+":8080";
                mMap.put("agencyIp",agencyIp);
            }
        String stringJson = StringUtil.getStringUtilNew().hashMapToJson(mMap); //参数包
        long time = StringUtil.getStringUtilNew().getTimeCurrent();
        String stirngSign = StringUtil.getStringUtilNew().getSign(Url.mStirngUpdate,stringJson,"null","0",time);
        Map map1 = StringUtil.getStringUtilNew().getMapNew(this,stringJson,"null","0", Url.mStirngUpdate,stirngSign,time);
        getLogger().info("版本更新update()--->fwq--"+ MyApplication.getApp().getFWQString()+"stringJson--"+stringJson);
        GreenTreeNetworkUtil.getInstance().doPost(this,MyApplication.getApp().getFWQString(),1,map1, new RequestDataCallback() {
            @Override public void onSuccess(String response) {
                getLogger().info("update()--->onSuccess--->"+"String--"+response);
                Gson gson = new Gson();
                Update update = gson.fromJson(response, Update.class);
                mUpdateList.add(update);
                LogUtil.eE("Gson",response);
                if(update.getCode().equals("1")){
                    if(update.getUs().equals("0")){
                        mUploadDialog.dismiss();
                        Toast.makeText(SetNewFiActivity.this, "已是最新的版本", Toast.LENGTH_SHORT).show();
                        //版本可用
                    }else if(update.getUs().equals("1")){
                       if(mUploadDialog !=null){mUploadDialog.dismiss();}
                        mUpdateDialog = new EditionDialog(SetNewFiActivity.this,mUpdateList,null);
                        mUpdateDialog.show();
                        //版本不可用
                    }else if(update.getUs().equals("2")){
                        if(mUploadDialog !=null){mUploadDialog.dismiss();}
                        mUpdateDialog = new EditionDialog(SetNewFiActivity.this,mUpdateList,null);
                        mUpdateDialog.show();
                    }else {
                        if(mUploadDialog !=null){mUploadDialog.dismiss();}
                    }
                }else {
                    if(mUploadDialog !=null){mUploadDialog.dismiss();}
                    Toast.makeText(SetNewFiActivity.this, getString(R.string.FWQ), Toast.LENGTH_SHORT).show();}
            }

            @Override
            public void onFailure(Throwable error) {
                if(mUploadDialog !=null){mUploadDialog.dismiss();}
                StringUtil.getStringUtilNew().getExceptionCode(SetNewFiActivity.this, error.toString());
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mUpdateList != null) {
            mUpdateList.clear();
        }

        if (mUpdateDialog != null) {
            mUpdateDialog.dismiss();
        }

        if (mUploadDialog != null) {
            mUploadDialog.dismiss();
        }

        if(mList !=null){mList.clear();}
    }

    /**
     * 跳转到权限设置界面
     */
    private void getAppDetailSettingIntent(){

        // vivo 点击设置图标>加速白名单>我的app
        //      点击软件管理>软件管理权限>软件>我的app>信任该软件
       /* Intent appIntent = getPackageManager().getLaunchIntentForPackage("com.iqoo.secure");
        if(appIntent != null){
            startActivity(appIntent);
            floatingView = new SettingFloatingView(this, "SETTING", getApplication(), 0);
            floatingView.createFloatingView();
            return;
        }

        // oppo 点击设置图标>应用权限管理>按应用程序管理>我的app>我信任该应用
        //      点击权限隐私>自启动管理>我的app
        appIntent = getPackageManager().getLaunchIntentForPackage("com.oppo.safe");
        if(appIntent != null){
            startActivity(appIntent);
            floatingView = new SettingFloatingView(this, "SETTING", getApplication(), 1);
            floatingView.createFloatingView();
            return;
        }*/

        LogUtil.eE("","getAppDetailSettingIntent....");
        if(getInformation.getNewGetInformation(this).getInfoPhone().equals("Huawei")){
            try {
                LogUtil.eE("","..................华为。。。");
                Intent intent = new Intent();
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                ComponentName comp = new ComponentName("com.huawei.systemmanager","com.huawei.permissionmanager.ui.MainActivity");//华为权限管理
                intent.setComponent(comp);
                startActivity(intent);
            } catch (Exception e) {
                e.printStackTrace();
                getToast("打开失败");
            }
        }else if(getInformation.getNewGetInformation(this).getInfoPhone().equals("miui")){
            try {
            Intent i = new Intent("miui.intent.action.APP_PERM_EDITOR");
            ComponentName componentName = new ComponentName("com.miui.securitycenter", "com.miui.permcenter.permissions.AppPermissionsEditorActivity");
            i.setComponent(componentName);
            i.putExtra("extra_pkgname", getPackageName());
            startActivity(i);
            } catch (Exception e) {
                e.printStackTrace();
                getToast("打开失败");
            }
        }else {
            LogUtil.eE("","..................其他。。。");
            Intent intent = new Intent();
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if(Build.VERSION.SDK_INT >= 9){
                intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                intent.setData(Uri.fromParts("we_package", getPackageName(), null));
            } else if(Build.VERSION.SDK_INT <= 8){
                intent.setAction(Intent.ACTION_VIEW);
                intent.setClassName("com.android.settings","com.android.settings.InstalledAppDetails");
                intent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
            }
           // startActivity(intent);
        }
    }
}
